#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>

#include <sys/types.h>
#include <sys/socket.h>
#include <unistd.h>
#include <netinet/in.h>
#include <arpa/inet.h>

#define SERVER_PORT 8080
#define BUF_SIZE    1024


int main(int argc, char **argv)
{
	int ret = 0;
	int sock_svr = 0;
	int sock_cln = 0;
	struct sockaddr_in sockaddr_svr = {0};
	struct sockaddr_in sockaddr_cln = {0};
	
	char info[BUF_SIZE] = {0};
	
	/* create socket */
	sock_svr = socket( AF_INET, SOCK_STREAM, 0 );
	if( sock_svr < 0 )
	{
		printf( "create socket error\n" );
		return -1;
	}
	
	/* sockaddr */
	sockaddr_svr.sin_family = AF_INET;
	sockaddr_svr.sin_port = htons(SERVER_PORT);
	sockaddr_svr.sin_addr.s_addr = INADDR_ANY;
	
	/* bind sock & sockaddr */
	ret = bind( sock_svr, (struct sockaddr*)&sockaddr_svr, sizeof(struct sockaddr) );
	if( ret < 0 )
	{
		printf( "bind socket error\n" );
		return -1;
	}
	
	ret = listen( sock_svr, 5 );
	if( ret < 0 )
	{
		printf( "tcp listen error \n" );
		return -1;
	}
	
	while( 1 )
	{
		unsigned int size_sockaddrIn =  sizeof(struct sockaddr_in);
		sock_cln = accept( sock_svr, (struct sockaddr*)&sockaddr_cln, &size_sockaddrIn );
		printf( "accept: %d\n", 1 );
		if( sock_cln < 0 )
		{
			printf( "tcp sock accept error: %d\n", sock_cln );
		}
		
		while( 1 )
		{
			ret = read( sock_cln, info, BUF_SIZE );
			if( ret <= 0 )
			{
				printf( "break\n" );
				break;
			}
			
			printf( "%s\n", info );			
		}
	}
	
	close( sock_svr );
	
	return 0;
}
